<template>
  <a-menu-item @click="showDrawer">
    修改登录密码
  </a-menu-item>
  <a-drawer v-model:visible="drawerVisible"
            :closable="false"
            destroy-on-close
            placement="right"
            title="修改密码"
            width="480px"
            @close="closeDrawer">
    <a-form :model="formState"
            :rules="formRules"
            layout="vertical"
            @finish="handleSubmit">
      <a-form-item label="原密码" prop="originalPassword">
        <a-input-password v-model:value="formState.originalPassword" placeholder="输入原密码"/>
      </a-form-item>
      <a-form-item label="新密码" prop="newPassword">
        <a-input-password v-model:value="formState.newPassword" placeholder="输入新密码"/>
      </a-form-item>
      <a-form-item label="确认新密码" prop="confirmPassword">
        <a-input-password v-model:value="formState.confirmPassword" placeholder="确认新密码"/>
      </a-form-item>
      <a-form-item>
        <a-button :loading="submitLoading" html-type="submit" type="primary">确认修改</a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script setup>
import {useRouter} from "vue-router";
import {clearProfile} from "../../../profile.js";

const drawerVisible = ref(false);
const showDrawer = () => {
  drawerVisible.value = true;
}
const closeDrawer = () => {
  drawerVisible.value = false;
}

const formState = reactive({
  originalPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const formRules = {
  originalPassword: [
    {required: true, message: '请输入原密码'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码'},
    {min: 6, max: 16, message: '最少需要输入 6 个字符'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码'}
  ]
};

const {execute, isLoading: submitLoading} = useApi({
  method: 'POST',
  url: '/system/employee/change-password',
  immediate: false
});
const router = useRouter();
const handleSubmit = async () => {
  await execute({
    data: formState
  });
  message.success('密码修改成功，请重新登录 ~');
  clearProfile();
  await router.push('/login');
};
</script>
